package com.kxmall.common.core.controller;

import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.kxmall.common.core.domain.R;
import com.kxmall.common.core.domain.model.LoginUser;
import com.kxmall.common.enums.DeviceType;
import com.kxmall.common.exception.ServiceException;
import com.kxmall.common.helper.LoginHelper;
import com.kxmall.common.utils.Page;
import com.kxmall.common.utils.PageData;
import org.apache.commons.lang3.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.UUID;

/**
 * web层App通用数据处理
 */
@Slf4j
public class BaseAppController {

    /**
     * 响应返回结果
     *
     * @param rows 影响行数
     * @return 操作结果
     */
    protected R<Void> toAjax(int rows) {
        return rows > 0 ? R.ok() : R.fail();
    }

    /**
     * 响应返回结果
     *
     * @param result 结果
     * @return 操作结果
     */
    protected R<Void> toAjax(boolean result) {
        return result ? R.ok() : R.fail();
    }

    /**
     * 页面跳转
     */
    public String redirect(String url) {
        return StrUtil.format("redirect:{}", url);
    }

    /**
     * 获取用户缓存信息
     */
    public LoginUser getLoginUser() {
        return LoginHelper.getLoginUser();
    }

    /**
     * 获取app用户缓存信息
     */
    public LoginUser getAppLoginUser() {
        if (!DeviceType.APP.equals(LoginHelper.getDeviceType())) {
            throw new ServiceException("用户类型不正确");
        }
        return LoginHelper.getLoginUser();
    }
    /**
     * 获取app用户缓存信息
     */
    public LoginUser getWebLoginUser() {
        if (!DeviceType.WEB.equals(LoginHelper.getDeviceType())) {
            throw new ServiceException("用户类型不正确");
        }
        return LoginHelper.getLoginUser();
    }
    /**
     * 获取登录用户id
     */
    public Long getUserId() {
        return LoginHelper.getUserId();
    }

    /**
     * 获取登录用户名
     */
    public String getUsername() {
        return LoginHelper.getUsername();
    }

    private String charReader(HttpServletRequest request) throws IOException {
        BufferedReader br = request.getReader();
        String str, wholeStr = "";
        while ((str = br.readLine()) != null) {
            wholeStr += str;
        }
        log.debug(wholeStr);
        return wholeStr;
    }

    public String getRequestData() throws IOException {
        return charReader(this.getRequest());
    }

    /**
     * new PageData对象
     */
    public PageData getPageData() throws IOException {
        String body = charReader(this.getRequest());
        if(log.isDebugEnabled()) {
            log.debug("getPageData {}", body);
        }
        if (body == null || body.length() == 0) {
            return null;
        }
        ObjectMapper mapper = new ObjectMapper();
        PageData map = mapper.readValue(body, PageData.class);
        return map;
    }

    public PageData getPageData(String json) throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        PageData map = mapper.readValue(json, PageData.class);
        return map;
    }

    /**
     * 获取SessionId
     * @return
     */
    public String getSessionId() {
        HttpSession session = getRequest().getSession();
        return (session != null) ? session.getId() : null;
    }

    public PageData getParamsData() throws IOException {
        String queryString = charReader(this.getRequest());
        String enc = "utf-8";
        PageData paramsMap = new PageData();
        if (queryString != null && queryString.length() > 0) {
            int ampersandIndex, lastAmpersandIndex = 0;
            String subStr, param, value;
            String[] paramPair, values, newValues;
            do {
                ampersandIndex = queryString.indexOf('&', lastAmpersandIndex) + 1;
                if (ampersandIndex > 0) {
                    subStr = queryString.substring(lastAmpersandIndex,
                            ampersandIndex - 1);
                    lastAmpersandIndex = ampersandIndex;
                } else {
                    subStr = queryString.substring(lastAmpersandIndex);
                }
                paramPair = subStr.split("=");
                param = paramPair[0];
                value = paramPair.length == 1 ? "" : paramPair[1];
                try {
                    value = URLDecoder.decode(value, enc);
                } catch (UnsupportedEncodingException ignored) {
                }
                paramsMap.put(param, value);
            } while (ampersandIndex > 0);
        }
        return paramsMap;
    }

    /**
     * 得到ModelAndView
     *
     * @return
     */
    public ModelAndView getModelAndView() {
        return new ModelAndView();
    }

    /**
     * 得到request对象
     *
     * @return
     */
    public HttpServletRequest getRequest() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes()).getRequest();
        return request;
    }

    /**
     * 得到response对象
     *
     * @return
     */
    public HttpServletResponse getResponse() {
        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes()).getResponse();
        return response;
    }

    /**
     * 得到32位的uuid
     *
     * @return
     */
    public String get32UUID() {
        return UUID.randomUUID().toString().trim().replaceAll("-", "");
    }

    /**
     * 得到分页列表的信息
     *
     * @return
     */
    public Page getPage() {
        return new Page();
    }

}
